package team.seekers.skill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import team.seekers.skill.entity.dao.User;
import team.seekers.skill.entity.vo.fore.add.UserAddVO;
import team.seekers.skill.entity.vo.fore.UserLearnStatusVO;
import team.seekers.skill.entity.vo.fore.detail.UserDetailVO;
import team.seekers.skill.result.Result;
import team.seekers.skill.service.UserService;
import team.seekers.skill.service.UserSeekSkillService;
import team.seekers.skill.common.utils.UserInfo;

import static team.seekers.skill.result.ResultCode.*;

/**
 * <p>
 *  用户相关基础信息和本站学习记录有关端口
 * </p>
 *
 * @author hbc
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/api/skill/user")
@Validated
public class UserController {

    @Autowired
    private UserSeekSkillService userSeekSkillService;
    @Autowired
    private UserService userService;

    @GetMapping("/getLearnStatus")
    @PreAuthorize("hasRole('ROLE_USER')")
    public Result getLearnStatus(){
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = userInfo.getUserId();
        UserLearnStatusVO learnStatusByUserId = userSeekSkillService.getLearnStatusByUserId(userId);
        if (learnStatusByUserId == null){
            return Result.fail(GET_FAIL);
        }
        return Result.success("userLearnStatusVO",learnStatusByUserId);
    }

    @PostMapping("/userRegister")
    public Result printAdmin(@RequestBody UserAddVO userAddVO) {
        //校验用户名
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userAddVO.getUsername());
        int count = userService.count(wrapper);
        if (count != 0){
            return Result.fail(USER_ACCOUNT_ALREADY_EXIST);
        }
        boolean save = userService.save(userAddVO);
        if(!save){
            return Result.fail(ACTION_FAIL).message("注册失败，请稍后重试");
        }
        return Result.success();
    }

    @GetMapping("/getUserInfo")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public Result getUserInfo(){
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = userInfo.getUserId();
        User user = userService.getById(userId);
        UserDetailVO userDetailVO = new UserDetailVO();
        BeanUtils.copyProperties(user, userDetailVO);
        return Result.success("userInfo", userDetailVO);
    }


}
